{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 8.1.3 随机森林模型的代码实现"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "和决策树模型一样，随机森林模型既可以做分类分析，也可以做回归分析。\n",
    "\n",
    "分别对应的模型为随机森林分类模型（RandomForestClassifier）及随机森林回归模型（RandomForestRegressor）。随机森林分类模型的基模型是分类决策树模型（详见5.1.2节），随机森林回归模型的基模型则是回归决策树模型（详见5.1.3节）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0]\n"
     ]
    }
   ],
   "source": [
    "# 随机森林分类模型简单代码演示如下所示：\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]\n",
    "y = [0, 0, 0, 1, 1]\n",
    "\n",
    "model = RandomForestClassifier(n_estimators=10, random_state=123)\n",
    "model.fit(X, y)\n",
    "\n",
    "print(model.predict([[5, 5]]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2.8]\n"
     ]
    }
   ],
   "source": [
    "# 随机森林回归模型简单代码演示如下所示：\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]\n",
    "y = [1, 2, 3, 4, 5]\n",
    "\n",
    "model = RandomForestRegressor(n_estimators=10, random_state=123)\n",
    "model.fit(X, y)\n",
    "\n",
    "print(model.predict([[5, 5]]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
